﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Net;
using Newtonsoft.Json.Linq;
using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;

namespace Coldairarrow.Util.Helper
{
    /// <summary>
    /// 钉钉帮助类
    /// </summary>
    public class DingHelper
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public DingHelper()
        {
        }

        /// <summary>
        /// 获取Access_Token
        /// </summary>
        /// <returns></returns>
        public static string getAccess_Token()
        {
            string Access_Token = "";
            #region 卓越时代
            //string appkey = "dingowkdclwlzmgzbjmh";
            //string appsecret = "sBXsk4rN5sGfq4VlS4W749QfOQOybyiVhRUbPlixfI1IJA-3giGAz2PaEcwpxf5h";
            #endregion
            #region 盛卓
            string appkey = "dingbsgr8ucqkkxp940t";
            string appsecret = "geWwqoo5AEEZC_pvX1KXEbSU8-Yn0s6Caddos0CSxe1xnz5IpZpGS0ACx-CnGXTI";
            #endregion
            string url = "https://oapi.dingtalk.com/gettoken?appkey=" + appkey + "&appsecret=" + appsecret;
            string res = HttpHelper.GetData(url);
            if (res != null)
            {
                JObject obj = JObject.Parse(res);
                if (obj["errcode"].ToString() == "0")
                {
                    Access_Token = obj["access_token"].ToString();
                }
            }
            return Access_Token;
        }

        /// <summary>
        /// 获取计件查询Access_Token
        /// </summary>
        /// <returns></returns>
        public static string getAccess_Token_Price()
        {
            string Access_Token = "";
            #region 盛卓
            string appkey = "ding7poge9o7ubmtg0dd";
            string appsecret = "3vPWtJDnMRy5ziGsYvypYhWmzFGwo5py9E1onJpefw82Fnk7UcAbCDezHYrh58nb";
            #endregion
            string url = "https://oapi.dingtalk.com/gettoken?appkey=" + appkey + "&appsecret=" + appsecret;
            string res = HttpHelper.GetData(url);
            if (res != null)
            {
                JObject obj = JObject.Parse(res);
                if (obj["errcode"].ToString() == "0")
                {
                    Access_Token = obj["access_token"].ToString();
                }
            }
            return Access_Token;
        }

        /// <summary>
        /// 获取用户简单信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static string getUserInfo(string code, string accessToken)
        {
            string result = null;
            string url = "https://oapi.dingtalk.com/user/getuserinfo?access_token=" + accessToken + "&code=" + code;
            result = HttpHelper.GetData(url);
            return result;
        }

        /// <summary>
        /// 获取用户详细信息
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static string getuserDetail(string accessToken, string userid)
        {
            string result = null;
            string url = "https://oapi.dingtalk.com/user/get?access_token=" + accessToken + "&userid=" + userid;
            result = HttpHelper.GetData(url);
            return result;
        }

        /// <summary>
        /// 获取部门详细信息（只支持中文）
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="departmentId">部门id</param>
        /// <returns></returns>
        public static string getDepartmentInfo(string accessToken, string departmentId)
        {
            string result = null;
            string url = "https://oapi.dingtalk.com/department/get?access_token=" + accessToken + "&id=" + departmentId;
            result = HttpHelper.GetData(url);
            return result;
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="input">推送用户列表</param>
        /// <returns></returns>
        public static string sendMessage(Util.Helper.DingInputDTO input)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");

            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.UseridList = string.Join(",", input.ExecutorIds.ToArray());
            //request.AgentId = long.Parse("1593169698");//卓越时代
            request.AgentId = long.Parse("1626898144");//盛卓
            request.ToAllUser = false;

            OapiMessageCorpconversationAsyncsendV2Request.MsgDomain msg = new OapiMessageCorpconversationAsyncsendV2Request.MsgDomain();
            //msg.Msgtype="text";
            //msg.Text=new OapiMessageCorpconversationAsyncsendV2Request.TextDomain();
            //msg.Text.Content="test123";
            //request.Msg_=msg;

            //msg.setMsgtype("image");
            //msg.setImage(new OapiMessageCorpconversationAsyncsendV2Request.Image());
            //msg.getImage().setMediaId("@lADOdvRYes0CbM0CbA");
            //request.setMsg(msg);

            //msg.setMsgtype("file");
            //msg.setFile(new OapiMessageCorpconversationAsyncsendV2Request.File());
            //msg.getFile().setMediaId("@lADOdvRYes0CbM0CbA");
            //request.setMsg(msg);

            //msg.setMsgtype("link");
            //msg.setLink(new OapiMessageCorpconversationAsyncsendV2Request.Link());
            //msg.getLink().setTitle("test");
            //msg.getLink().setText("test");
            //msg.getLink().setMessageUrl("test");
            //msg.getLink().setPicUrl("test");
            //request.setMsg(msg);

            //msg.Msgtype="markdown";
            //msg.Markdown=(new OapiMessageCorpconversationAsyncsendV2Request.MarkdownDomain());
            //msg.Markdown.Text="##### text";
            //msg.Markdown.Title="### Title";
            //request.Msg_=msg;

            msg.Oa = (new OapiMessageCorpconversationAsyncsendV2Request.OADomain());
            msg.Oa.Head = (new OapiMessageCorpconversationAsyncsendV2Request.HeadDomain());
            msg.Oa.Head.Text = "您有一条新消息";
            msg.Oa.Body = (new OapiMessageCorpconversationAsyncsendV2Request.BodyDomain());
            msg.Oa.Body.Content = input.Str;
            msg.Oa.MessageUrl =input.MessgUrl;
            msg.Msgtype = "oa";
            request.Msg_ = msg;

            //msg.ActionCard=(new OapiMessageCorpconversationAsyncsendV2Request.ActionCardDomain());
            //msg.ActionCard.Title="<font color='red'>异常消息发送通知</font>";
            //msg.ActionCard.Markdown= "<font color='red'>异常消息发送通知</font>";
            //msg.ActionCard.SingleTitle="测试测试<br>sssss";
            //msg.ActionCard.SingleUrl = "https://www.baidu.com";
            //msg.Msgtype="action_card";
            //request.Msg_=msg;

            OapiMessageCorpconversationAsyncsendV2Response response = client.Execute(request, getAccess_Token());
            return response.Body;
        }
    }
    /// <summary>
    /// 钉钉推送消息传参实体
    /// </summary>
    public class DingInputDTO
    {
        /// <summary>
        /// 推送用户id列表
        /// </summary>
        public List<string> ExecutorIds { get; set; }

        /// <summary>
        /// 抄送用户id列表
        /// </summary>
        public List<string> ParticipantIds { get; set; }
        /// <summary>
        /// 推送文字
        /// </summary>
        public string Str { get; set; }
        /// <summary>
        /// 表单ID
        /// </summary>
        public string BillId { get; set; }
        /// <summary>
        /// 跳转路径
        /// </summary>
        public string MessgUrl { get; set; }
    }
}
